/*
 *
 */

#import "UIImageView+CutToResize.h"

#define kDefaultImage         @"lv_image_default_background.png"
#define kDefaultImageSmall    @"lv_image_default_background_small.png"
#define kDefaultImageMedium   @"lv_image_default_background_medium.png"

@implementation UIImageView (CutToResize)


+ (void)imagesArrayCutToResize:(NSMutableArray *)imagesArray :(CGSize)imageSize
{
    for (int i=0; i<imagesArray.count; i++) {
        UIImage *image = nil;
        image = [imagesArray objectAtIndex:i];
        image = [self imageCutToResize:image :imageSize];
        [imagesArray replaceObjectAtIndex:i withObject:image];
    }
}


+ (UIImage*)imageCutToResize:(UIImage *)image :(CGSize)imageSize
{
//    float sizeWidToHeiDiv = imageSize.width / imageSize.height;
//    float imgWidToHeiDiv = image.size.width / image.size.height;
//    if (sizeWidToHeiDiv == 1 && imgWidToHeiDiv == 1) {
//        return image;
//    }
//    CGRect rect; 
//    if (imgWidToHeiDiv > sizeWidToHeiDiv) {
//        //图片矮宽
//        //减去左右两边
//        float newWidth = sizeWidToHeiDiv * image.size.height;   //新图片的宽度，长度不变
//        rect = CGRectMake((image.size.width - newWidth)/2.0, 0, newWidth, image.size.height);    //合乎比例的图片尺寸
//    }
//    else {
//        //图片高瘦
//        //减去上下两头
//        float newHeight = image.size.width / sizeWidToHeiDiv;
//        rect = CGRectMake(0, (image.size.height - newHeight)/2.0, image.size.width, newHeight);
//    }
    CGFloat width = image.size.width;
    CGFloat height = image.size.height;
    float verticaRadio = height/imageSize.height;
    float horizontalRadio = width/imageSize.width;
    int verticaRadioInt = verticaRadio *100;
    int horizontaRadioInt = horizontalRadio *100;
    //相差很少的就不剪切了
    if (verticaRadioInt == horizontaRadioInt) {
        return image;
    }
    CGRect rect; 
    if (verticaRadio > horizontalRadio) {
        //图片高瘦
        //减去上下两头
        float newHeight = imageSize.height*horizontalRadio;
        rect = CGRectMake(0, (height - newHeight)/2.0, width, newHeight);
    }else{
        //图片矮宽
        //减去左右两边
        float newWidth = imageSize.width * verticaRadio;   //新图片的宽度，长度不变
        rect = CGRectMake((width - newWidth)/2.0, 0, newWidth, height);    //合乎比例的图片尺寸
    }

    CGImageRef cgimg = CGImageCreateWithImageInRect([image CGImage], rect); //合乎比例的图片
    //图片自动压缩到目标尺寸
    UIGraphicsBeginImageContextWithOptions(imageSize,NO,[[UIScreen mainScreen] scale]);
    
    UIImage *tempImage = [UIImage imageWithCGImage:cgimg];

    [tempImage drawInRect:CGRectMake(0, 0, imageSize.width, imageSize.height)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    CGImageRelease(cgimg);

    return scaledImage;
}

@end
